$(function() {
  var link = 'http://120.78.130.251:9527';
  var bigfarmland_w ;
  var bigfarmland_h ;
  var bigfarmland_name ;
  var species_num;
  var expType;
  //var bigfarmland_ID = 'bigfarm15602426210586348';
  var w,h;
  var type;
  var container = document.getElementById("parent")
  var window_width = window.innerWidth
  var container_w;
  var container_h;
  const farmlandAry_C = new Array();
  const farmlandAry_G = new Array();
  var sel = document.getElementById('sel')
  var string = window.location.search;
  var bigfarmland_ID = string.split('=')[1];
  console.log(bigfarmland_ID);
  var formData = new FormData()  //创建一个forData
  formData.append('bigfarmId',bigfarmland_ID)
  $.ajax({
    type: 'POST',
    url: link+'/bigfarm/getBigfarm',
    contentType: 'application/json; charset=utf-8',
    data:formData,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    dataType: 'json',
    success: function(data) {
      //console.log(data.data.width + '--' + data.data.length)
      bigfarmland_w=data.data.length;
      bigfarmland_h=data.data.width;
      bigfarmland_name=data.data.name;
      var propotion = parseFloat(bigfarmland_h/bigfarmland_w)

      container.style.height = parseFloat(propotion* window_width*0.9) + 'px'
      container.style.width = 0.8 * window_width +'px'

      container_w = container.offsetWidth;
      container_h = container.offsetHeight;
    },
    error: function(data) {
      console.log("获取信息失败")
    }
  })

  $("#sel").change(function(){
    var selected=$(this).children('option:selected').val();
    var species = document.getElementById("num");
    var notice1 = document.getElementById("num_notice");
    var type = document.getElementById("type");
    var notice2 = document.getElementById("type_notice");
    if(selected=="greenhouse"){
      species.style.visibility = "visible";
      notice1.style.visibility = "visible"
      type.style.visibility = "visible";
      notice2.style.visibility = "visible"
    }else if(selected=="common"){
      species.style.visibility = "hidden";
      notice1.style.visibility = "hidden"
      type.style.visibility = "hidden";
      notice2.style.visibility = "hidden"
    }
  });

    reading()

  $('.state').click(function(e) {
    e.preventDefault();
    var farmlandId = $('#pId').val()
    w = $('#width').val()
    h = $('#height').val()
    var regular = $('#sel').val();
// startX, startY 为鼠标点击时初始坐标
// diffX, diffY 为鼠标初始坐标与 box 左上角坐标之差，用于拖动
    var startX, startY, diffX, diffY;
// 是否拖动，初始为 false
    var dragging = false;
// 鼠标按下
    if(farmlandId === ' ' || w==='' || h==='' || regular === ''){
      alert("请输入完整信息")
    }
    else {
      if(w>0 && h>0 && w<=bigfarmland_w && h<=bigfarmland_h) {
        var active_box = document.createElement("div");
        //active_box.innerHTML = farmlandId;
        active_box.id = farmlandId ;
        active_box.setAttribute('id', farmlandId);
        active_box.setAttribute('type',regular);
        active_box.setAttribute('w',w);
        active_box.setAttribute('h',h);
        active_box.style.width = parseFloat(container_w * w / bigfarmland_w) + 'px';
        active_box.style.height = parseFloat(container_h * h / bigfarmland_h) + 'px';
        console.log(active_box.style.width+ '====' +active_box.style.height);
        //active_box.id = "active_box";
        //active_box.className = "box";
        if(regular === 'common'){
          active_box.classList.add('box');
          active_box.style.background = '#dff0d8';
          active_box.style.position = 'absolute';
          active_box.style.border = '1px solid #000000';
          active_box.style.opacity = '0.5'
          active_box.style.cursor = 'move';
          var text = document.createTextNode(farmlandId);
          active_box.style.fontSize = "20px";
          active_box.appendChild(text);
          container.appendChild(active_box);
          farmlandAry_C.push(farmlandId);
        }
        if(regular === 'greenhouse'){
          species_num = $('#num').val();
          expType = $('#type').val();
          active_box.classList.add('greenhouse');
          active_box.style.background = '#ffcc00';
          active_box.style.position = 'absolute';
          active_box.style.border = '1px solid #000000';
          active_box.style.opacity = '0.5'
          active_box.style.cursor = 'move';
          var text = document.createTextNode(farmlandId);
          active_box.style.fontSize = "20px";
          active_box.appendChild(text);
          container.appendChild(active_box);
          farmlandAry_G.push(farmlandId);
        }
        active_box.onmousedown = function(event) {
          var ev = event || window.event;
          event.stopPropagation();
          var disX = ev.clientX - active_box.offsetLeft;
          var disY = ev.clientY - active_box.offsetTop;
          document.onmousemove = function(event) {
            var ev = event || window.event;
            active_box.style.left = ev.clientX - disX + "px";
            active_box.style.top = ev.clientY - disY + "px";
            active_box.style.cursor = "move";
          }
        }
        active_box.onmouseup = function() {
          document.onmousemove = null;
          this.style.cursor = "default";
        }
      }
      else {
        alert("无效的数据,横向宽度应在0-"+bigfarmland_w+"米，纵向宽度应在0-"+bigfarmland_h+"米")
      }
      active_box.ondblclick = function() {
        var res = confirm('是否确认删除？')
        if (res == true) {
          document.getElementById('parent').removeChild(this);
            console.log(active_box.getAttribute('type'))
            if(active_box.getAttribute('type') === 'common'){
              var index1 = farmlandAry_C.indexOf(this);
              farmlandAry_C.splice(index1, 1);

            }
            if(active_box.getAttribute('type') === 'greenhouse'){
              var index2 = farmlandAry_G.indexOf(this);
              farmlandAry_G.splice(index2,1);
            }

          // console.log(this)
          // console.log(myGrids)
        }
        else {
        }
      }
    }
    //return w,h;
  })

  $('.cancel').click(function(e) {
    e.preventDefault();
    var res = confirm('是否确认删除？')
    if (res === true) {
      var oDiv = $('.box');
      document.getElementById('parent').removeChild(oDiv[oDiv.length - 1])
      if(oDiv.getAttribute('type') === 'common'){
        farmlandAry_C.length--;
      }
      if(oDiv.getAttribute('type') === 'greenhouse'){
        farmlandAry_G.length--;
      }
    }

    return false
  })

  $('.save').click(function(e) {
    e.preventDefault();
    console.log(farmlandAry_C);
    var json = [];
    var json1 = [];
    var json2 = [];
    for (var i = 0; i < farmlandAry_C.length; i++) {

      var w = document.getElementById(farmlandAry_C[i]).getAttribute('w');
      console.log(w)
      var h =document.getElementById(farmlandAry_C[i]).getAttribute('h');
      var move_X = document.getElementById(farmlandAry_C[i]).offsetLeft
      var move_Y = document.getElementById(farmlandAry_C[i]).offsetTop
      var movex = move_X + document.getElementById(farmlandAry_C[i]).offsetWidth
      var movey = move_Y + document.getElementById(farmlandAry_C[i]).offsetHeight

      var row1 = {
        'name' : farmlandAry_C[i],
        'bigfarmId': bigfarmland_ID,
        'width' : w,
        'length' : h,
        'x': move_X,
        'y': move_Y,
        'x2': movex,
        'y2': movey
      }
      json1.push(row1);
      json.push(row1);
      //console.log(row);
    }

    for (var i = 0; i < farmlandAry_G.length; i++) {
      var w = document.getElementById(farmlandAry_G[i]).getAttribute('w');
      var h =document.getElementById(farmlandAry_G[i]).getAttribute('h');
      var move_X = document.getElementById(farmlandAry_G[i]).offsetLeft
      var move_Y = document.getElementById(farmlandAry_G[i]).offsetTop
      var movex = move_X + document.getElementById(farmlandAry_G[i]).offsetWidth
      var movey = move_Y + document.getElementById(farmlandAry_G[i]).offsetHeight

      var row2 = {
        'name' : farmlandAry_G[i],
        'farmlandId': bigfarmland_ID,
        'width' : w,
        'length' : h,
        'moveX': move_X,
        'moveY': move_Y,
        'moveX1': movex,
        'moveY1': movey,
        'num':species_num,
        'expType':expType,
        'rows': 2
      }
      json2.push(row2);
      json.push(row2);
      //console.log(row);
    }
    $.ajax({
      type: 'POST',
      url: link+'/bigfarm/addFarmPlan',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(json1),
      dataType: 'json',
      success: function(message) {
        alert("保存成功")
        console.log("success")
      },
      error: function(message) {
        alert('提交数据失败！')
        return
      }
    })

    $.ajax({
      type: 'POST',
      url: link+'/bigfarm/addGreenhousePlan',
      contentType: 'application/json; charset=utf-8',
      data: JSON.stringify(json2),
      dataType: 'json',
      success: function(message) {
        alert("保存成功")
        console.log("success")
      },
      error: function(message) {
        alert('提交数据失败！')
        return
      }
    })



    //生成文件
    var filename = bigfarmland_name
    var str_json = JSON.stringify(json)
    export_raw(filename, str_json)


    html2canvas($("#parent"), {
      onrendered: function(canvas) {
        canvas.id = "mycanvas";
        var mainwh = $("#parent").width();
        var mainhg = $("#parent").height();
        var img = convertCanvasToImage(canvas);
        console.log(img);
        $("#dw").append(img) //添加到展示图片div区域
        img.onload = function() {
          img.onload = null;
          canvas = convertImageToCanvas(img, 0, 0, mainwh, mainhg); //设置图片大小和位置
          img.src = convertCanvasToImage(canvas).src;
          $(img).css({
            background:"#fff"
          });
          //调用下载方法
          if(browserIsIe()){ //假如是ie浏览器
            DownLoadReportIMG(img.src);
          }else{
            download(img.src)
          }
        }
      }
    });

  })

  function export_raw(filename, content) {
    var eleLink = document.createElement('a')
    eleLink.download = filename
    eleLink.style.display = 'none' // 字符内容转变成blob地址
    var blob = new Blob([content])
    eleLink.href = URL.createObjectURL(blob) // 触发点击
    document.body.appendChild(eleLink)
    eleLink.click() // 然后移除
    document.body.removeChild(eleLink)
  }




  //绘制显示图片
  function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png"); //获得图片地址
    return image;
  }
  //生成canvas元素，相当于做了一个装相片的框架
  function convertImageToCanvas(image, startX, startY, width, height) {
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(image, startX, startY, width, height, 0,0, width, height); //在这调整图片中内容的显示（大小,放大缩小,位置等）
    return canvas;
  }
  function DownLoadReportIMG(imgPathURL) {
    //如果隐藏IFRAME不存在，则添加
    if (!document.getElementById("IframeReportImg"))
      $('<iframe style="display:none;" id="IframeReportImg" name="IframeReportImg" onload="DoSaveAsIMG();" width="0" height="0" src="about:blank"></iframe>').appendTo("body");
    if (document.all.IframeReportImg.src != imgPathURL) {
      //加载图片
      document.all.IframeReportImg.src = imgPathURL;
    }
    else {
      //图片直接另存为
      DoSaveAsIMG();
    }
  }
  function DoSaveAsIMG() {
    if (document.all.IframeReportImg.src != "about:blank")
      window.frames["IframeReportImg"].document.execCommand("SaveAs");
  }
  // 另存为图片
  function download(src) {
    var $a = $("<a></a>").attr("href", src).attr("download", bigfarmland_name+ ".png");
    $a[0].click();
  }
  //判断是否为ie浏览器
  function browserIsIe() {
    if (!!window.ActiveXObject || "ActiveXObject" in window)
      return true;
    else
      return false;
  }

  $('.upload').click(function(e) {
    e.preventDefault();
    var formData = new FormData()  //创建一个forData
    formData.append('file', $('#file2')[0].files[0]) //把file添加进去  name命名为img
    formData.append('bigfarmId',bigfarmland_ID)
    $.ajax({
      url: link+'/bigfarm/updateBigfarmImg',
      data: formData,
      type: "POST",
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      success: function(data) {
        alert("上传成功");
      },
      error: function() {
        console.log("上传失败");
      }
    })
  })

  function reading() {
    var formData1 = new FormData()  //创建一个forData
    formData1.append('bigfarmId',bigfarmland_ID)
    $.ajax({
      url: link+'/bigfarm/getFarms',
      type: 'POST',
      data:formData1,
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      dataType: 'json',
      success: function(data) {
        console.log(data);
        var number1 = data.total;
        var json1 = data.rows;
        for (var i = 0; i < number1; i++) {
          var farmlandName = json1[i].name;
          var x1 = json1[i].x;
          var y1 = json1[i].y;
          var x2 = json1[i].x2;
          var y2 = json1[i].y2;
          //var type = json1[i].type;
          var box1 = document.createElement('div');
          //box.innerHTML = farmlandName;
          box1.style.marginLeft = x1 + 'px';
          box1.style.marginTop = y1 + 'px';
          box1.style.width = (x2-x1) + 'px';
          box1.style.height = (y2-y1) + 'px';
          //box.classList.add('box');
          box1.classList.add('box');
          box1.style.background = '#dff0d8';
          box1.style.position = 'absolute';
          box1.style.border = '1px solid #000000';
          box1.style.opacity = '0.5'
          box1.style.cursor = 'move';
          var text1 = document.createTextNode(farmlandName);
          box1.style.fontSize = "20px";
          box1.appendChild(text1);
          container.appendChild(box1);


          box1.ondblclick = function() {
            var res = confirm('是否确认删除？')
            if (res == true) {
              document.getElementById('parent').removeChild(this);
              var index1 = farmlandAry_C.indexOf(this);
              var index2 = farmlandAry_G.indexOf(this);
              if (index1 > -1 && index2 > -1) {
                  farmlandAry_C.splice(index1, 1);
                }
            }
            else {
            }
          }
        }
      },
      error: function() {
        console.log("读取失败")
      }
    })

    $.ajax({
      url: link+'/bigfarm/getGreenhouses',
      type: 'POST',
      data:formData1,
      async: false,
      cache: false,
      contentType: false,
      processData: false,
      dataType: 'json',
      success: function(data) {
        console.log(data);
        var number2 = data.total;
        var json2 = data.rows;
        for (var i = 0; i < number2; i++) {
          var farmlandName = json2[i].name;
          var x1 = json2[i].moveX;
          var y1 = json2[i].moveY;
          var x2 = json2[i].moveX1;
          var y2 = json2[i].moveY1;
          //var type = json2[i].type;
          var box2 = document.createElement('div');
          //box.innerHTML = farmlandName;
          box2.style.marginLeft = x1 + 'px';
          box2.style.marginTop = y1 + 'px';
          box2.style.width = (x2-x1) + 'px';
          box2.style.height = (y2-y1) + 'px';
          //box.classList.add('box');
          box2.classList.add('greenhouse');
          box2.style.background = '#ffcc00';
          box2.style.position = 'absolute';
          box2.style.border = '1px solid #000000';
          box2.style.opacity = '0.5'
          box2.style.cursor = 'move';

          var text2 = document.createTextNode(farmlandName);
          box2.style.fontSize = "20px";
          box2.appendChild(text2);
          container.appendChild(box2);


          box2.ondblclick = function() {
            var res = confirm('是否确认删除？')
            if (res == true) {
              document.getElementById('parent').removeChild(this);
              var index1 = farmlandAry_C.indexOf(this);
              var index2 = farmlandAry_G.indexOf(this);
              if (index1 > -1 && index2 > -1) {
                  farmlandAry_G.splice(index2,1);
              }
            }
            else {
            }
          }
        }
      },
      error: function() {
        console.log("读取失败")
      }
    })
  }
})


